"""
PyQt5版GUI工具
"""
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
import sys
from ui.Ui_main_window import Ui_MainWindow
import threading
import datetime
import enum
from utils.net_utils import *


# 定义枚举，记录当前连接状态，保存消息内容和状态值
class ConnectStatus(enum.Enum):
    DISCONNECT = 0, "连接网络"
    CONNECTED = 1, "断开连接（已连接）"
    CONNECTING = 2, "正在连接..."
    CONNECT_ERR = 3, "连接失败，请稍后重试..."

    def __str__(self):
        return self.name

    @property
    def status(self):
        return self.value[0]

    @property
    def tip(self):
        return self.value[1]


class MainWindow(QMainWindow):
    append_text_signal = pyqtSignal(str)

    def __init__(self):
        super().__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.tcp_client: socket.socket = None
        self.conn_status = ConnectStatus.DISCONNECT

        self.__init_ui()

        self.append_text_signal.connect(self.append_text)

    def append_text(self, text):
        self.ui.edit_recv.appendPlainText(text)

    def run_tcp_client(self, ip, port):
        self.update_connect_status(ConnectStatus.CONNECTING)
        self.tcp_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            addr = (ip, int(port))
            self.tcp_client.connect(addr)
        except:
            self.update_connect_status(ConnectStatus.CONNECT_ERR)
            return

        local_ip, local_port = self.tcp_client.getsockname()
        self.ui.cb_local_ip.setCurrentIndex(self.ui.cb_local_ip.findText(local_ip))
        self.ui.edit_local_port.setText(str(local_port))

        self.update_connect_status(ConnectStatus.CONNECTED)

        print("连接成功，本机信息ip: {} port: {}".format(local_ip, local_port))

        try:
            while self.tcp_client is not None:
                recv_data = self.tcp_client.recv(2048)
                if recv_data:
                    msg = recv_data.decode("gbk")
                    print("接收到数据：", msg)
                    # 生成当前时间戳
                    now = datetime.datetime.now()
                    time_str = now.strftime("%H:%M:%S")

                    show_text = "【{} {}:{}】{}".format(time_str, ip, port, msg)
                    self.append_text_signal.emit(show_text)
                    if msg.find("love") != -1:
                        self.tcp_client.send("Love you too！\r\n".encode("gbk"))
                else:
                    break
        finally:
            try:
                self.tcp_client.close()
            finally:
                self.tcp_client = None
                self.update_connect_status(ConnectStatus.DISCONNECT)

    def update_connect_status(self, status):
        if status == ConnectStatus.CONNECT_ERR:
            self.conn_status = ConnectStatus.DISCONNECT
            self.ui.btn_connect.setText(self.conn_status.tip)
        else:
            self.conn_status = status
            self.ui.btn_connect.setText(self.conn_status.tip)
        # 显示状态栏提示消息
        self.statusBar().showMessage(status.tip)

    def send(self):
        if self.tcp_client is None:
            return
        text = self.ui.edit_send.toPlainText()
        print("发送数据：", text)
        self.tcp_client.send(f"{text}\r\n".encode())

    def connect(self):
        if self.conn_status == ConnectStatus.CONNECTING:
            return
        elif self.conn_status != ConnectStatus.DISCONNECT:
            if self.tcp_client is not None:
                self.tcp_client.shutdown(socket.SHUT_RD)
                self.tcp_client = None
            self.update_connect_status(ConnectStatus.DISCONNECT)
            return

        # 获取网络模式
        mode = self.ui.cb_mode.currentText()
        # 获取输入IP
        ip = self.ui.edit_target_ip.text()
        # 获取输入端口
        port = self.ui.edit_target_port.text()
        print("mode: {} ip: {} port: {}".format(mode, ip, port))

        # 开启线程，创建TCP客户端，连接到服务器
        t = threading.Thread(target=self.run_tcp_client, args=(ip, port), daemon=True)
        t.start()
    def save(self):
        # 保存操作
        print("save")

    def open(self):
        # 打开操作
        print("open")

    def undo(self):
        # 撤销操作
        pass
    def __init_ui(self):
        # 创建工具栏
        toolbar = QToolBar(self)
        self.addToolBar(toolbar)

        # 创建保存按钮
        save_action = QAction('保存', self)
        save_icon = QIcon("./images/ic_menu_save.png")
        save_action.setIcon(save_icon)
        save_action.triggered.connect(self.save)
        toolbar.addAction(save_action)

        # 创建打开按钮
        open_action = QAction('打开', self)
        open_icon = QIcon("./images/ic_launcher_folder_open.png")
        open_action.setIcon(open_icon)
        open_action.triggered.connect(self.open)
        toolbar.addAction(open_action)

        # 创建撤销按钮
        undo_action = QAction('撤销', self)
        undo_action.triggered.connect(self.undo)
        toolbar.addAction(undo_action)

        # 给连接按钮绑定事件
        self.ui.btn_connect.clicked.connect(self.connect)

        # 获取所有本机IP
        local_ips = get_local_ip()
        # 添加到IP输入框
        self.ui.cb_local_ip.addItems(local_ips)
        # 默认选中第一个
        self.ui.cb_local_ip.setCurrentIndex(0)

        self.ui.btn_send.clicked.connect(self.send)

        self.ui.actionExit.triggered.connect(QApplication.quit)


def main():
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()
